<template>
	<el-popover ref="popover" class="popover-reference" placement="bottom-start" :width="inputWidth || 400" :disabled="disabled" v-model="visible" @show="popoverShow" @hide="hide" @after-leave="popoverHide" popper-class="el-select-dropdown is-multiple padding-no mp-micro" trigger="click">
		<div>
			<!-- 查询 -->
			<div class="search">
				<el-input class="el-input--radius" prefix-icon="el-icon-search" size="medium" readonly-ui="readonly" type="text" v-model="query" placeholder="查询" v-if="isSearch">
				</el-input>
			</div>
			<div class="member__line"></div>
			<ul class="el-select-dropdown__list">
				<li class="el-select-dropdown__item" v-for="(item, index) in optionsArrShow" :key="index" @click="nodeClick(item)" :class="{ selected: item.select, 'is-disabled': item.disabled }" v-show="item.visible">
					<radioLabel class="radio-label" :disableClose="true" :title="item.label">
            <icon-svg v-if="isIcon" :iconClass="item.label"></icon-svg>
            <span v-else>{{ item.label }}</span>
          </radioLabel>
				</li>
				<!-- 无匹配数据 -->
				<li v-if="optionsArrShow.length === 0" class="el-select-dropdown__empty">
					无匹配数据
				</li>
			</ul>
		</div>
		<inputContent v-bind="$attrs" style="height:auto" v-clickoutside="hideOnly" :disabled="disabled" :clear="clear" :visible="visible" :selected="clearable && currentSelect.length !== 0" slot="reference">
			<div v-for="(one, index) in currentSelect" :key="index" style="margin-right:6px">
				<radioLabel @close="close(index)">
          <icon-svg v-if="isIcon" :iconClass="one.label"></icon-svg>
          <span v-else>{{ one.label }}</span>
        </radioLabel>
			</div>
		</inputContent>
	</el-popover>
</template>

<script>
// eslint-disable-next-line no-restricted-imports
import { isEqual } from 'lodash';
import Emitter from '@/afterSales/mixins/emitter';
import inputContent from './inputContent.vue';
import Clickoutside from 'element-ui/src/utils/clickoutside';
import radioLabel from './radioLabel.vue';

export default {
  name: 'm7Select',
  mixins: [Emitter],
  props: {
    isSearch: {
      type: Boolean,
      default: true
    },
    clearable: {
      type: Boolean,
      default: true
    },
    name: String,
    id: String,
    value: {
      required: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    autoComplete: {
      type: String,
      default: 'off'
    },
    multiple: Boolean,
    multipleLimit: {
      type: Number,
      default: 0
    },
    placeholder: {
      type: String,
      default () {
        return '请选择';
      }
    },
    valueKey: {
      type: String,
      default: 'value'
    },
    defaultProps: {
      type: Object,
      default: () => {
        return { value: 'value', label: 'label' };
      }
    },
    options: {
      type: Array,
      default: () => []
    },
    isIcon: {
      type: Boolean,
      default: false
    },
    inputWidth: {
      type: Number,
      default: 0
    }
  },
  directives: {
    Clickoutside
  },
  data () {
    return {
      tagName: '',
      visible: false,
      query: '',
      maxIndex: 100,
      timer: ''
    };
  },
  components: {
    inputContent,
    radioLabel
  },
  computed: {
    optionsArr () {
      const label = this.defaultProps.label;
      const value = this.defaultProps.value;
      const options = this.options || [];
      const self = this;
      return options.map(item => {
        let select = false;
        if (self.multiple) {
          select = (self.value || []).some(one => one === item[value]);
        } else {
          select = self.value === item[value];
        }
        let visible = true;
        if (item.isDelete) {
          visible = false;
        }
        if (self.query && item[label] && item[label].indexOf(self.query) === -1) {
          visible = false;
        }
        return {
          label: item[label],
          value: item[value],
          visible,
          select,

          disabled: item.disabled
        };
      });
    },
    optionsArrShow () {
      const optionsArr = this.optionsArr;
      return optionsArr.filter((item, index) => {
        if (index < this.maxIndex && item.visible) {
          return true;
        }
      });
    },
    currentSelect () {
      let value;
      if (this.multiple) {
        value = this.value || [];
      } else {
        value = [this.value];
      }
      return this.optionsArr.filter(item => {
        return value.includes(item.value);
      });
    }
  },
  watch: {
    visible (val) {
      this.$emit('visible-change', val);
    }
  },
  methods: {
    // 删除
    close (index) {
      if (this.multiple) {
        const value = JSON.parse(JSON.stringify(this.value || []));
        console.log(value);
        value.splice(index, 1);
        this.$emit('input', value);
      } else {
        this.$emit('input', '');
      }
    },
    // 分批加载
    handler () {
      this.maxIndex = 100;
      window.clearInterval(this.timer);
      this.timer = window.setInterval(() => {
        this.maxIndex += 200;
        if (this.maxIndex > this.options.length) {
          window.clearInterval(this.timer);
        }
      }, 10);
    },
    nodeClick (item) {
      if (item.disabled) {
        return;
      }
      if (this.multiple) {
        this.query = '';
        const value = JSON.parse(JSON.stringify(this.value || []));
        const index = value.indexOf(item.value);
        if (index !== -1) {
          value.splice(index, 1);
        } else {
          value.push(item.value);
        }
        this.$emit('input', value);
        this.emitChange(value);
      } else {
        // 单选
        this.visible = false;
        this.query = '';
        this.$emit('input', item.value);
        this.emitChange(item.value);
      }
    },
    hide () {
      this.visible = false;
      this.$emit('blur');
    },
    hideOnly () {
      this.visible = false;
    },
    clear () {
      this.$emit('input', this.multiple ? [] : null);
    },
    emitChange (val, obj) {
      if (!isEqual(this.value, val)) {
        this.$emit('change', val);
        this.dispatch('ElFormItem', 'el.form.change', val);
      }
    },
    popoverShow () {
      this.$nextTick(() => {
        this.handler();
      });
    },
    popoverHide () {
      this.$nextTick(() => {
        this.query = '';
        this.maxIndex = 100;
        window.clearInterval(this.timer);
      });
    },
    focus () {
      this.visible = true;
    }
  },
  mounted () {
    // this.inputWidth = this.$refs.reference.getBoundingClientRect().width
    // 配合v-clickoutside指令使用，点击popover内的元素，弹框不消失
    this.popperElm = this.$refs.popover.$refs.popper;
  },
  created () {
    if (this.multiple && !Array.isArray(this.value)) {
      this.$emit('input', []);
    }
    if (!this.multiple && Array.isArray(this.value)) {
      this.$emit('input', '');
    }
    this.$on('fieldReset', () => {
      this.dispatch('ElFormItem', 'el.form.change');
    });
  },
  beforeDestroy () {
    window.clearInterval(this.timer);
  }
};
</script>
<style scoped lang="stylus">
.search {
	padding 8px 16px
	box-sizing border-box
}
.tag-text {
	color #fff
	border-radius 4px
	padding 0 8px
	font-size 12px
	// line-height 24px
	&+.tag-text {
		margin-left 5px
	}
}
.member__line {
	width 100%
	height 1px
	background #000000
	opacity 0.05
	position absolute
	top 54px
}
.selected:hover {
	.el-icon-arrow-up {
		display none
	}
	.el-icon-circle-close {
		display block
	}
}
.tag-max {
	max-width 60px
	display inline-block
	text-overflow ellipsis
	overflow hidden
	white-space nowrap
}
.el-select-dropdown__list {
	max-height 280px
	overflow-y auto
}
.el-select-dropdown__item {
	padding 0 12px
	height 40px
	line-height 40px
}
.radio-label {
	max-width 92%
	overflow hidden
	white-space nowrap
	transform translateY(6px)
	text-overflow ellipsis
}
</style>
